import request from '@/utils/request'
import { HomeAction, RootThunkAction } from '@/types/store'
import { ApiResponse, Channel } from '@/types/data'
import { hasToken } from '@/utils/storage'
import { getChannels, setChannels } from '@/utils/storageChannel'

// 获取用户频道信息
// 1.登录用户:正常发请求,
// 2.没有登录:从本地取,本地没有数据在发请求
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch) => {
    if (hasToken()) {
      const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )
      console.log(res.data.data.channels)
      // 保存到 redux
      dispatch({
        type: 'home/getUserChannel',
        payload: res.data.data.channels
      })
    } else {
      const channels = getChannels()
      if (channels.length === 0) {
        const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
          '/user/channels'
        )
        console.log(res.data.data.channels)
        // 保存到 redux
        dispatch({
          type: 'home/getUserChannel',
          payload: res.data.data.channels
        })
        setChannels(res.data.data.channels)
      } else {
        // 保存到 redux
        dispatch({
          type: 'home/getUserChannel',
          payload: channels
        })
      }
    }
  }
}

export const changeActive = (id: string): HomeAction => {
  return {
    type: 'home/changeActive',
    payload: id
  }
}

export const getAllChannel = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    console.log(res.data.data.channels)
    // 保存到 redux
    dispatch({
      type: 'home/getAllChannel',
      payload: res.data.data.channels
    })
  }
}

// 添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取到所有的userChannels
    const { userChannels } = getState().home
    // 如果登录了，发送请求获取频道信息
    if (hasToken()) {
      await request.patch('/user/channels', {
        channels: [channel]
      })
    } else {
      // 如果没有登录，将频道数据保存到本地
      // 将channels数据保存本地
      setChannels([...userChannels, channel])
    }
    // 保存到redux ---- 视图更新
    dispatch({
      type: 'home/getUserChannel',
      payload: [...userChannels, channel]
    })
  }
}

// 删除频道
export function delChannel (id: string): RootThunkAction {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    if (hasToken()) {
      // 用户登录了，发送请求进行删除
      await request.delete('/user/channels', {
        data: {
          channels: [id]
        }
      })
    } else {
      // 如果没有登录，本地删除一条数据
      setChannels(userChannels.filter((item) => item.id.toString() !== id))
    }
    // 统一更新到redux
    // dispatch({
    //   type: 'home/saveUserChannels',
    //   payload: userChannels.filter((item) => item.id !== id)
    // })
    dispatch(getUserChannel())
  }
}
